#pragma once
#include <iostream>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"
#include "InetAddr.hpp"
const std::string default_name = "./dictionary.txt";
class Dict
{
public:
    Dict(const std::string &file_name = default_name)
        : _file_name(file_name)
    {
    }

    // 建立字典文件中- 英汉映射
    bool Load_Dict()
    {
        // 定义分隔符
        std::string sp = ":";
        // 打开文件
        std::ifstream file(_file_name);
        if (!file.is_open())
        {
            LOG(FATAL) << "翻译字典无法打开";
            return false;
        }
        std::string line;
        while (std::getline(file, line))
        {
            size_t pos = line.find(sp); // 查找每行分隔符位置
            if (pos == std::string::npos)
            {
                LOG(DEBUG) << "文本格式有误" << "->" << line;
                continue;
            }
            // 字符串提取
            std::string key = line.substr(0, pos);    // 从开始到分隔符前
            std::string value = line.substr(pos + 1); // 从分隔符后到结束

            std::pair<std::string, std::string> dictionary = std::make_pair(key, value);
            _dict.insert(dictionary);
        }
        file.close();
        return true;
    }

    std::string Trans(const std::string &word, InetAddr &client)
    {
        auto it = _dict.begin();
        it = _dict.find(word);
        if (it == nullptr)
        {
            LOG(DEBUG) << "进入到了翻译模块, [" << client.Ip() << " : " << client.Port() << "]# " << word << "->None";
            return "None";
        }
        else
        {
            LOG(DEBUG) << "进入到了翻译模块, [" << client.Ip() << " : " << client.Port() << "]# " << word << "->" << it->second;
            return it->second;
        }
    }

    ~Dict() {}

private:
    std::string _file_name;
    std::unordered_map<std::string, std::string> _dict;
};